package com.yeskery.nut.extend.auth;

import com.yeskery.nut.core.*;

import java.util.List;
import java.util.logging.Logger;

/**
 * 请求上下文插件，用于请求线程数据存储，基于ThreadLocal实现
 * @author sprout
 * @version 1.0
 * 2022-11-01 17:46
 */
public class RequestContextPlugin extends AbstractAuthPlugin {

    /** 日志对象 */
    private static final Logger logger = Logger.getLogger(RequestContextPlugin.class.getName());

    /** 请求上下文处理器 */
    private final RequestContextHandler requestContextHandler;

    /**
     * 构建请求上下文插件
     * @param requestContextHandler 请求上下文处理器
     */
    public RequestContextPlugin(RequestContextHandler requestContextHandler) {
        this.requestContextHandler = requestContextHandler;
    }

    @Override
    public boolean beforeHandle(Request request, Response response, Execution execution, Controller controller) throws Exception {
        boolean passed = super.beforeHandle(request, response, execution, controller);
        if (!passed) {
            return false;
        }
        RequestContext.initialize();
        List<KeyAndValue<String, ?>> requestContextSources = requestContextHandler.getRequestContextSources(request);
        if (requestContextSources != null) {
            for (KeyAndValue<String, ?> keyAndValue : requestContextSources) {
                if (!RequestContext.set(keyAndValue.getKey(), keyAndValue.getValue())) {
                    logger.info("RequestContext Set Key[" + keyAndValue.getKey()
                            + "] And Value[" + keyAndValue.getValue() + "] Failure.");
                }
            }
        }
        return true;
    }

    @Override
    public void afterHandle(Request request, Response response, Controller controller, Exception e) throws Exception {
        RequestContext.remove();
    }
}
